<template lang='pug'>
  van-popup(
    v-model="currentValue"
    position="bottom"
    )
    .image.border-1px(:style="{backgroundSize: `${isImage ? percent : 0}% 100%`, backgroundPosition: '0 0'}")
      |{{!isImage ? '图片' : !isReady ? '请稍后...' : isUpLoad ? '上传中' : '图片'}}
      input(type="file" multiple accept="image/*" @change="upLoad($event, 1)")
    .video.border-1px(:style="{backgroundSize: `${!isImage ? percent : 0}% 100%`, backgroundPosition: '0 0'}")
      |{{isImage ? '视频' : !isReady ? '请稍后...' : isUpLoad ? '上传中' : '视频'}}
      input(type="file" accept="video/*" @change="upLoad($event, 2)")
    .cancel.border-t-1px(@click="currentValue = false") 取消

</template>

<script type='text/ecmascript-6'>
  import {compressWithSize} from '~/assets/js/compress'
  import imageCorrection from '~/assets/js/imageCorrection'
  
  const qiniuDomain = 'http://img.tukeshare.com/'
  const MAX_SIZE = 500000
  const MAX_LENGTH = 10000
  const [videoReg, imageReg] = [/^video\//i, /^image\//i]
  /*eslint-disable */
  export default {
    props: {
      value: Boolean,
      isCompress: {
        type: Boolean,
        default: true
      },
      text: {
        type: String,
        default: '修改封面图'
      },
    },
    data() {
      return {
        currentValue: this.value,
        files: [],
        percents: [],
        isUpLoad: false,
        c: 0,
        w: 0,
        h: 0,
        isReady: true,
        fileType: 1
      }
    },
    watch: {
      currentValue: {
        handler: function (bol) {
          this.$emit('input', bol)
        },
        immediate: true,
      },
      value: {
        handler: function (bol) {
          this.currentValue = bol
        },
        immediate: true,
      }
    },
    beforeMount() {
      this._loadScript()
    },
    mounted() {
      // if (this.fileType === 0) {
      //   this.$refs.file.removeAttribute('multiple')
      // }
      // let w = this.$refs.svg.clientWidth
      // let h = this.$refs.svg.clientHeight
      // this.w = w
      // this.h = h
      // let c = w * 0.25 * Math.PI * 2
      // this.c = c
    },
    computed: {
      isImage() { return this.fileType === 1 },
      percent() {
        if (!this.percents || !this.percents.length) return 0
        let num = this.percents.reduce((a, b) => a + b)
        return num / (this.percents.length * 100) * 100
      }
    },
    methods: {
      _loadScript () {
        let $script = document.createElement('script')
        document.head.appendChild($script)
        $script.src = 'https://unpkg.com/qiniu-js@2.2.0/dist/qiniu.min.js'
        $script.onload = () => {
          // this.$toast('七牛上传准备完毕')
        }
      },
      makeRandom(size = 3) {
        let num = ~~(Math.random() * 1000)
        let arr = []
        arr.length = size
        arr.fill(0)
        return Number((num + arr.join()).substring(0, size))
      },
      upLoad(event, fileType, maxSize = MAX_SIZE, maxLength = MAX_LENGTH) {
        this.fileType = fileType

        this.percents = []
        this.files = []
        let files = event.target.files
        if (files.length > maxLength) {
          event.target.value = ''
//          event.target.outerHTML=event.target.outerHTML;
          alert('最多上传' + maxLength + '个文件')
          return
        }
        files = Array.prototype.slice.call(files)
        let canUpload = true, hasVideo, hasImg
//        let [videoReg, imageReg] = [/^video\//i, /^image\//i]
//        let txt = videoReg.test(type) ? '视频' : imageReg.test(type) ? '图片' : '其它'
//        let videoReg = /\.(AVI|wma|rmvb|flash|mp4|mid|3GP|flv|mpeg)$/i
//        let imgReg = /\.(jpg|jpeg|png|gif|bmp|tiff|svg|raw)$/i
        files.forEach(file => {
          if (file.type.match(imageReg)) hasImg = true
          if (file.type.match(videoReg)) hasVideo = true
        })

        let sizeArr = files.map(file => file.size)
        let size = sizeArr.reduce((a, b) => a + b)
        if (size > (maxSize * 1024 * 1024)) canUpload = false
        if (!canUpload) {
          this.$toast('限制' + maxSize + 'M, 请在手机相册裁剪后上传')
          event.target.value = ''
          return
        }
        this.isReady = false
        this.$post('/api/platform/qiniu/token', {}).then(resp => {
          let token = resp.data.token
          let pArr = []
          files.forEach((file, index) => {
            let key = encodeURI(Date.now() + this.makeRandom() + '.' + file.name.split('.')[1])
            let p = new Promise((resolve, reject) => {
              this.uploadWithSDK(file, index, token, key, () => {
                resolve()
              })
            })
            pArr.push(p)
          })
          this.isReady = true
          this.isUpLoad = true
          Promise.all(pArr).then(() => {
            if (this.percent >= 100) {
              this.$toast('上传成功')
              this.$emit('complete', this.files)
              this.percents = []
            } else {
              this.percents = []
              this.$toast('上传失败')
            }
            this.isUpLoad = false
            event.target.value = ''
          }).catch(() => {
            this.isUpLoad = false
            event.target.value = ''
            this.$toast('上传失败')
          })
        }).catch(() => { this.$toast('上传失败') })

      },
      async uploadWithSDK(file, index, token, key, callback = () => {}) {
        let json = {}
        this.files.push(json)
        this.percents.push(0)
        var config = {
          useCdnDomain: false,
          disableStatisticsReport: false,
          retryCount: 6,
          region: qiniu.region.z2
        };
        var putExtra = {
          fname: "",
          params: {},
          mimeType: null
        };
        let fname = file.name
        var observable;
        if (file) {
          let blob = await imageCorrection(file)
          const P = this.isCompress ? compressWithSize(blob) : Promise.resolve(blob)
          blob = await P
          putExtra.params["x:name"] = key.split(".")[0];
          var error = (err) => {
            callback()
          };
          var complete = (res) => {
            callback()
            let type
            if (fname.match(/\.(jpg|jpeg|png|gif|bmp|tiff|svg|raw)$/i)) {
              // 检测上传的是否是图片
              type = 1
            } else { type = 2 }
            let resUrl = qiniuDomain + res.data.key
//            this.files[index].type = type
//            this.files[index].linkUrl = resUrl
            this.$set(this.files[index], 'type', type)
            this.$set(this.files[index], 'linkUrl', resUrl)
//            this.$emit('complete', type, resUrl)
          };

          var next = (response) => {
            // 这里对每个chunk更新进度，并记录已经更新好的避免重复更新，同时对未开始更新的跳过
            var chunks = response.chunks||[];
            var total = response.total;
            // 这里对每个chunk更新进度，并记录已经更新好的避免重复更新，同时对未开始更新的跳过
            if (total.percent) this.percents.splice(index, 1, total.percent)
//            if (total.percent) this.$set(this.files[index], 'percent', total.percent)
          }
          var subObject = {
            next: next,
            error: error,
            complete: complete
          };
          var subscription;
          // 调用sdk上传接口获得相应的observable，控制上传和暂停
          // console.log(file, key, token)
          // observable = qiniu.upload(file, key, token, putExtra, config);
          observable = qiniu.upload(blob, key, token, putExtra, config);
          subscription = observable.subscribe(subObject);
//            subscription.unsubscribe();
        }
      }
    }
  }
</script>

<style lang='stylus' rel='stylesheet/stylus' scoped>

@import '~assets/stylus/variable.styl'
@import '~assets/stylus/mixin.styl'
 
.image, .video
  position relative
  padding 1.5rem 0
  text-align center
  // background-color red
  background-image: linear-gradient(to right, $color-main, $color-main);
  background-repeat: no-repeat;
  background-position: 0 0;
  border-1px($color-border-bl)
  input
    width 100%
    opacity 0
    position absolute
    top 0
    bottom 0
    left 0
    right 0
.cancel
  // margin-top 5rem
  padding 2rem 0
  text-align center
  border-t-1px($color-border)
  color $color-main
</style>
